package service;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.SwingWorker;

import model.Stack;

/**
 * 
 * @author Alexey Kuprin
 * 
 */
public class StackMonitor extends SwingWorker<Void, Void> {
	private int sleep = 1000;
	private boolean active = true;
	private List<Stack> stacksNotified;
	private OutdatedStackMonitor outdatedStackListener;

	public StackMonitor(Observer stackAlertListener) {
		super();
		stacksNotified = new ArrayList<Stack>();
		outdatedStackListener = new OutdatedStackMonitor();
		outdatedStackListener.addObserver(stackAlertListener);
	}

	private class OutdatedStackMonitor extends Observable {
		public void monitor() {
			try {
				while (active) {
					List<Stack> outdatedStacks = Service.getInstance()
							.checkForOutdatedStacks();
					if (outdatedStacks != null && outdatedStacks.size() > 0)
						for (Stack stack : outdatedStacks)
							if (!stacksNotified.contains(stack)) {
								stacksNotified.add(stack);
								setChanged();
								notifyObservers(stack);
							}

					setChanged();
					notifyObservers();
					Thread.sleep(sleep);
				}

				while (!active)
					Thread.sleep(sleep);
			} catch (InterruptedException e) {
				// nothing to handle
			} finally {
				monitor();
			}
		}
	}

	@Override
	protected Void doInBackground() {
		System.out.println("Stack monitor started");
		outdatedStackListener.monitor();

		return null;
	}

	public int getSleep() {
		return sleep;
	}

	public void setSleep(int sleep) {
		this.sleep = sleep;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}
}
